#!/usr/bin/env python3
# $Id: test3-8.py 7c6bb3d1dea5 2012/08/26 01:44:08 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: 7c6bb3d1dea5 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-08-26 01:44:08Z $"

import socket

def main(dest_name):
   dest_addr = socket.gethostbyname(dest_name)
   port = 33434
   max_hops = 30
   icmp = socket.getprotobyname('icmp')
   udp = socket.getprotobyname('udp')
   ttl = 1
   while True:
      recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
      send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
      send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
      recv_socket.bind(("", port))
      # sendto("No Umlaut".encode("ascii"), ("localhost", 514))
      send_socket.sendto("".encode("ascii"), (dest_name, port))
      # send_socket.sendto("",  (dest_name, port))
      curr_addr = None
      curr_name = None
      try:
         _, curr_addr = recv_socket.recvfrom(512)
         curr_addr = curr_addr[0]
         try:
            curr_name = socket.gethostbyaddr(curr_addr)[0]
         except socket.error:
            curr_name = curr_addr
      except socket.error:
         pass
      finally:
         send_socket.close()
         recv_socket.close()

         if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
         else:
            curr_host = "*"

         print("%d\t%s" % (ttl, curr_host))

         ttl += 1
         if curr_addr == dest_addr or ttl > max_hops:
            break

if __name__ == "__main__":
   main('www.gmail.com')
